#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
游戏核心逻辑
包含所有游戏数据和计算逻辑
"""

import json
import time
import random
import threading
from typing import Dict, List, Any
from dataclasses import dataclass, asdict
from utils.events import EventManager
from utils.save_manager import SaveManager

@dataclass
class Currency:
    """货币数据类"""
    name: str
    symbol: str
    price: float
    change_rate: float
    volatility: float  # 波动率

@dataclass
class Equipment:
    """设备数据类"""
    id: str
    name: str
    level: int
    hashrate: float  # 算力 H/s
    price: float     # 升级价格
    power_consumption: float  # 功耗
    description: str

@dataclass
class Player:
    """玩家数据类"""
    name: str
    profession: str
    level: int
    experience: int
    skills: Dict[str, int]

class GameCore:
    """游戏核心类"""
    
    def __init__(self):
        self.save_manager = SaveManager()
        self.event_manager = EventManager()
        
        # 游戏状态
        self.running = False
        self.mining_active = False
        self.last_update = time.time()
        
        # 玩家数据
        self.player = Player(
            name="矿工",
            profession="新手",
            level=1,
            experience=0,
            skills={"efficiency": 1, "luck": 1, "energy": 1}
        )
        
        # 货币系统 - 只保留BTC
        self.currencies = {
            "BTC": Currency("比特币", "BTC", 50000.0, 0.0, 0.05),
        }
        
        # 玩家持有的货币 - 只有BTC
        self.wallet = {
            "BTC": 0.0,
        }
        
        # 设备系统
        self.equipment = {
            "basic_miner": Equipment(
                id="basic_miner",
                name="基础矿机",
                level=1,
                hashrate=1.0,
                price=0.00000010,
                power_consumption=100,
                description="入门级挖矿设备"
            ),
            "advanced_miner": Equipment(
                id="advanced_miner", 
                name="高级矿机",
                level=0,
                hashrate=10.0,
                price=0.00000100,
                power_consumption=500,
                description="性能更强的挖矿设备"
            ),
            "quantum_miner": Equipment(
                id="quantum_miner",
                name="量子矿机", 
                level=0,
                hashrate=100.0,
                price=0.00010000,
                power_consumption=1000,
                description="未来科技挖矿设备"
            )
        }
        
        # 固定挖掘BTC
        self.current_mining_currency = "BTC"
        
        # 游戏统计
        self.statistics = {
            "total_mined": 0.0,
            "total_earned": 0.0,
            "mining_time": 0.0,
            "lucky_finds": 0,
            "upgrades_bought": 0
        }
        
        # 事件系统
        self.recent_events = []
        
        # 启动后台线程
        self.start_background_threads()
    
    def start_background_threads(self):
        """启动后台线程"""
        self.running = True
        
        # 挖矿线程
        mining_thread = threading.Thread(target=self._mining_loop, daemon=True)
        mining_thread.start()
        
        # 市场更新线程
        market_thread = threading.Thread(target=self._market_loop, daemon=True)
        market_thread.start()
        
        # 随机事件线程
        event_thread = threading.Thread(target=self._event_loop, daemon=True)
        event_thread.start()
        
        # 自动保存线程
        auto_save_thread = threading.Thread(target=self._auto_save_loop, daemon=True)
        auto_save_thread.start()
    
    def _mining_loop(self):
        """挖矿主循环"""
        while self.running:
            if self.mining_active:
                current_time = time.time()
                delta_time = current_time - self.last_update
                
                # 计算挖矿收益
                total_hashrate = self.get_total_hashrate()
                if total_hashrate > 0:
                    # 基础挖矿收益 (每秒)
                    base_earning = total_hashrate * 0.00000001 * delta_time
                    
                    # 应用技能加成
                    efficiency_bonus = 1 + (self.player.skills["efficiency"] - 1) * 0.1
                    earning = base_earning * efficiency_bonus
                    
                    # 添加到BTC钱包
                    self.wallet["BTC"] += earning
                    self.statistics["total_mined"] += earning
                    self.statistics["mining_time"] += delta_time
                    
                    # 幸运挖掘检查
                    if random.random() < 0.001 * self.player.skills["luck"]:  # 0.1% * 幸运值
                        bonus = earning * random.uniform(2, 10)
                        self.wallet["BTC"] += bonus
                        self.add_event(f"🍀 幸运挖掘！获得额外 {bonus:.8f} BTC!")
                        self.statistics["lucky_finds"] += 1
                
                self.last_update = current_time
            
            time.sleep(0.1)  # 100ms更新间隔
    
    def _market_loop(self):
        """市场价格更新循环"""
        while self.running:
            for symbol, currency in self.currencies.items():
                # 随机价格波动
                change = random.gauss(0, currency.volatility)
                currency.price *= (1 + change)
                currency.change_rate = change * 100
                
                # 防止价格过低
                if currency.price < 0.01:
                    currency.price = 0.01
            
            time.sleep(30)  # 30秒更新一次市场价格
    
    def _event_loop(self):
        """随机事件循环"""
        events = [
            "⚡ 网络优化完成，挖矿效率提升10%！",
            "📰 市场利好消息，币价上涨！", 
            "🔧 设备检修完成，算力恢复正常！",
            "💡 发现新的挖矿算法，收益增加！",
            "⚠️ 电力故障，挖矿暂停3秒...",
            "🎯 幸运时刻：下次升级半价！"
        ]
        
        while self.running:
            time.sleep(random.uniform(60, 300))  # 1-5分钟随机事件
            if self.mining_active:
                event = random.choice(events)
                self.add_event(event)
    
    def _auto_save_loop(self):
        """自动保存循环"""
        while self.running:
            time.sleep(1)  # 每秒保存一次
            try:
                data = self.get_game_data()
                self.save_manager.save_game(data)
            except Exception as e:
                # 静默失败，避免过多错误日志
                pass
    
    def get_total_hashrate(self) -> float:
        """获取总算力"""
        total = 0.0
        for equipment in self.equipment.values():
            if equipment.level > 0:
                total += equipment.hashrate * equipment.level
        return total
    
    def get_earning_rate(self) -> float:
        """获取每秒收益率"""
        total_hashrate = self.get_total_hashrate()
        efficiency_bonus = 1 + (self.player.skills["efficiency"] - 1) * 0.1
        return total_hashrate * 0.00000001 * efficiency_bonus
    
    def start_mining(self):
        """开始挖矿"""
        self.mining_active = True
        self.last_update = time.time()
        self.add_event("🚀 开始挖矿！")
    
    def stop_mining(self):
        """停止挖矿"""
        self.mining_active = False
        self.add_event("⏹️ 停止挖矿！")
    
    def upgrade_equipment(self, equipment_id: str) -> bool:
        """升级设备"""
        if equipment_id not in self.equipment:
            return False
            
        equipment = self.equipment[equipment_id]
        price = equipment.price * (1.5 ** equipment.level)
        
        if self.wallet["BTC"] >= price:
            self.wallet["BTC"] -= price
            equipment.level += 1
            equipment.price = price * 1.5  # 价格上涨
            
            self.statistics["upgrades_bought"] += 1
            self.add_event(f"📈 {equipment.name} 升级到 Lv.{equipment.level}!")
            return True
        return False
    
    def switch_mining_currency(self, currency: str):
        """切换挖矿币种 - 已固定为BTC"""
        # 固定为BTC，不再支持切换
        pass
    
    def add_event(self, message: str):
        """添加事件日志"""
        timestamp = time.strftime("%H:%M:%S")
        self.recent_events.insert(0, f"[{timestamp}] {message}")
        if len(self.recent_events) > 20:  # 保留最近20条
            self.recent_events.pop()
        
        # 触发事件回调
        self.event_manager.trigger_event("new_event", message)
    
    def get_game_data(self) -> Dict:
        """获取游戏数据快照"""
        return {
            "player": asdict(self.player),
            "wallet": self.wallet,
            "equipment": {k: asdict(v) for k, v in self.equipment.items()},
            "currencies": {k: asdict(v) for k, v in self.currencies.items()},
            "statistics": self.statistics,
            "current_mining_currency": self.current_mining_currency,
            "mining_active": self.mining_active
        }
    
    def save_game(self):
        """保存游戏"""
        try:
            data = self.get_game_data()
            self.save_manager.save_game(data)
            self.add_event("💾 游戏已保存")
        except Exception as e:
            self.add_event(f"❌ 保存失败: {str(e)}")
    
    def load_game(self):
        """加载游戏"""
        try:
            data = self.save_manager.load_game()
            if data:
                # 恢复玩家数据
                if "player" in data:
                    self.player = Player(**data["player"])
                
                # 恢复钱包
                if "wallet" in data:
                    self.wallet.update(data["wallet"])
                
                # 恢复设备
                if "equipment" in data:
                    for eq_id, eq_data in data["equipment"].items():
                        if eq_id in self.equipment:
                            self.equipment[eq_id] = Equipment(**eq_data)
                
                # 恢复统计
                if "statistics" in data:
                    self.statistics.update(data["statistics"])
                
                # 恢复挖矿币种
                if "current_mining_currency" in data:
                    self.current_mining_currency = data["current_mining_currency"]
                
                self.add_event("📂 游戏数据已加载")
            else:
                self.add_event("🎮 开始新游戏！")
        except Exception as e:
            self.add_event(f"❌ 加载失败: {str(e)}")
    
    def shutdown(self):
        """关闭游戏"""
        self.running = False
        self.save_game()